# coding=utf-8
import json
import logging
import requests
from WorkflowScript.RDC_PushPackage_py3.Authorization import *
# 控制台输出移除SSL认证警告
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

proxies = {
    "http": "127.0.0.1:8888"
}
# 初始化session，后续请求就能自动带上cookies
sess = requests.session()

# RDC登录后的授权信息字符串
Authorization = AuthorizationString


def httphead(Authorization):
    RDCheaders = {
        'Host': 'rdc.mingyuanyun.com',
        'Connection': 'keep-alive',
        'Accept': 'application/json, text/plain, */*',
        # 'Authorization': 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjIzQjRCRkZGMTI3QzA5QTNFNzg5OTlCRTlERjYxQ0MyNzQ3NTdGQjUiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJJN1NfX3hKOENhUG5pWm0tbmZZY3duUjFmN1UifQ.eyJuYmYiOjE2MDYzMTQ4MjAsImV4cCI6MTYwNjQ4NzYyMCwiaXNzIjoiaHR0cHM6Ly9hdXRoLm1pbmd5dWFueXVuLmNvbSIsImF1ZCI6WyJodHRwczovL2F1dGgubWluZ3l1YW55dW4uY29tL3Jlc291cmNlcyIsImRlZmF1bHRBcGkiLCJyZGMtcmVzb3VyY2VjZW50ZXItc2VydmljZSIsInJkYy1maWxlLXNlcnZpY2UiXSwiY2xpZW50X2lkIjoicmRjIiwic3ViIjoiYzllMGMwYzYtNGYwYy00NGJlLWE1NDAtM2M1NjNiZGViMjBlIiwiYXV0aF90aW1lIjoxNjA2MzE0ODE5LCJ1c2VyIjoie1wiTmFtZVwiOlwi5ZC06bmP77yI5q2m5rGJ5Lqn5ZOB77yJXCIsXCJVc2VyTmFtZVwiOlwid3VwMDZcIixcIkVtYWlsXCI6XCJ3dXAwNkBtaW5neXVhbnl1bi5jb21cIixcIlBob25lXCI6XCIxNzYwNzE5MDQ0MFwiLFwiQXZhdGFyRmlsZU5hbWVcIjpcImh0dHA6Ly9wa2cubWluZ3l1YW55dW4uY29tL1VzZXIvQXZhdGFycy81Z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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty',
        'Referer': 'https://rdc.mingyuanyun.com/projects/46',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9'
    }
    return RDCheaders


def publish_customers(RDCversion):
    """
    通过RDC版本号，获取对应版本的客户信息，提供做包请求通过RDC版本号判断对应客户是否能做包,返回列表
    :param RDCversion: RDC版本号
    :return: 返回列表，如：[{"version":"2.0.27.13","customers":[{客户A信息},{客户B信息}]}]
    """
    url = 'https://rdc.mingyuanyun.com/rdc-service/api/v2/apps/107/versions/' + RDCversion + '/publish-customers?unInstall=false'
    r = sess.get(url, headers=httphead(Authorization), proxies=proxies, verify=False)
    status_code = r.status_code
    if status_code == 200:
        resp = json.loads(r.text)
        versions = resp["result"]["versions"]
        # print(resp["result"]["versions"])
        # 客户A：{"customerName":"东营文渊置业有限公司","customerERP":"8568c093-ee87-47da-a026-061f89d8953c,gzlERP,","tenantId":"","tenantName":"","isLock":false,"isHasCustomize":false,"isApproval":false,"isHavePdTask":false,"labels":[{"id":"7ee87420-d3b8-4dd8-898d-0de47d9f3a76","name":"拓新客户","type":1}],"isFeatureApproval":false,"isHotfixApproval":false},
        # versions获取到rdc版本对应的客户列表[{"version":"2.0.27.13","customers":[{客户A},{客户B}]}]
        return versions
    elif status_code == 401:
        resp = json.loads(r.text)
        error = resp["error"]["message"]
        print(u"请求返回信息：%s\nAuthorization已失效，请重新获取！" % error)
        exit()
    else:
        print(u"publish_customers请求出错，状态码：%s" % (str(status_code)))
        exit()


def get_tagId(RDCversion):
    """
    通过rdc版本号，获取对应的tagId，提供给做包请求使用，迭代版与稳定版的包数量超过80，则要调整limit数量
    :param RDCversion:
    :return:
    """
    url = "https://rdc.mingyuanyun.com/rdc-service/api/v2/apps/107/versions?orderBy=0&type=1&tagType=0&q=&for=all&offset=0&limit=80"
    r = sess.get(url, headers=httphead(Authorization), proxies=proxies, verify=False)
    resp = json.loads(r.text)
    items = resp["result"]["items"]
    # print(items)
    for item in items:
        if item["name"] == RDCversion:
            tagId = item["tagId"]
            # print(u"version版本Id:" + str(tagId))
            return tagId


def makeupdatepackage(versionId, desc, customers):
    """
    做更新包请求，如果有多个客户情况下需要判断客户版本是否做包
    :param versionId: 从get_tagId获取到的tagId
    :param desc: 文字推包描述，可以手动输入，或者推包文件得到
    :param customers: 需要做包客户信息集合
    :return: 返回字典{"publishUpdatePackageId":29262, "sourceVersion":"2.0.33.1","publishVersion","2.0.36.1"}
    """
    url = "https://rdc.mingyuanyun.com/rdc-service/api/v2/apps/107/versions/" + str(versionId) + "/makeupdatepackage"
    headers = httphead(Authorization)
    headers["Content-Type"] = "application/json;charset=UTF-8"
    data = {"appId": 107, "versionId": versionId, "desc": desc, "unInstall": False, "tenantIds": "",
            "customers": customers}
    status_code = 504
    count = 0
    PackageInfo = {}
    #  经常做包超时失败，默认给个失败返回码504，不为504再推包
    while status_code == 504:
        r = sess.post(url, headers=headers, json=data, proxies=proxies, verify=False)
        status_code = r.status_code
        if status_code != 504:
            resp_json = json.loads(r.text)
            # 获取publishUpdatePackageId给推包请求用,sourceVersion,publishVersion用于记录推包日志
            PackageInfo["sourceVersion"] = resp_json["result"]["sourceVersion"]
            PackageInfo["publishUpdatePackageId"] = resp_json["result"]["publishUpdatePackageId"]
            PackageInfo["publishVersion"] = resp_json["result"]["publishVersion"]
            PackageInfo["customerImageBuildRecordId"] = resp_json["result"]["customerImageBuildRecordId"]
            # delFiles必须转换成元祖，否则comfirm_files进行remove时，delFiles的内容也会remove掉
            delFiles = tuple(resp_json["result"]["delFiles"])
            comfirm_files = resp_json["result"]["delFiles"]
            # 获取需要删除的文件路径list，如果不存在含debug的文件路径，则可能删除了生产需要的文件，打印出来，确认是否退出推包。
            # 设置排除检查关键字，如果文件路径存在此关键字，则默认是允许删除的文件
            remove_keyword = remove_keyword_check
            for file in delFiles:
                for keyword in remove_keyword:
                    if keyword in file.lower():
                        comfirm_files.remove(file)
            if len(comfirm_files) != 0:
                print(u"待删除的文件可能有问题，请确认：")
                for file in comfirm_files:
                    print(file)
                comfirm = input("确认是否推包，退出按任意键，推包按y：\n")
                if comfirm.lower() != "y":
                    exit()
            print(u"制作更新包完成，准备推包。。。")
            return PackageInfo
        count += 1
        print(u"第%s次制作更新包请求响应码: %s，准备重试。。。" % (str(count), str(status_code)))


def get_customer_version(cust, versionlist, wf_package_list, distinct):
    """
    通过模糊或精确匹配的客户名称，得到具体客户名称的版本号和客户信息
    :param cust:
    :param versionlist:
    :param wf_package_list: 版本信息字典的列表，包含RDC版本，描述desc的工作流版本，已推包客户等等，用于匹配当前客户版本信息
    :distinct: 精确匹配或者模糊匹配客户开关，None模糊匹配，"y"精确匹配
    :return: 返回客户版本，客户信息的字典列表[{'cur_version': '2.0.27.8', 'customer_info': {'isHavePdTask': False, 'isLock': False, 'customerName': '绿地集团', 'labels': [{'type': 1, 'id': '25be2ac9-17e4-4870-bbdf-bd2762ca89fa', 'name': '千亿客户'}], 'isFeatureApproval': False, 'isHasCustomize': False, 'tenantName': '', 'customerERP': 'b1cb6621-f0a2-4700-8089-cf53ea19a6f7,gzlERP,', 'isHotfixApproval': False, 'tenantId': '', 'isApproval': False}},...]
    """
    customer_dict_list = []
    for customer in versionlist:
        for cust_dict in customer["customers"]:
            # 精确匹配开关为None，则使用in进行模糊匹配
            if distinct is None:
                if cust in cust_dict["customerName"]:
                    version_customer_dict = {}
                    # print(cust_dict)
                    # print(cust_dict["customerName"]+customer["version"])
                    # 得到版本：客户信息字典
                    version_customer_dict["cur_version"] = customer["version"]
                    version_customer_dict["customer_info"] = cust_dict
                    # 因为客户可能存在同名，将当前版本，客户信息字典加入到列表
                    customer_dict_list.append(version_customer_dict)
            # 否则进行精确匹配客户信息
            else:
                if cust == cust_dict["customerName"]:
                    version_customer_dict = {}
                    # print(cust_dict)
                    # print(cust_dict["customerName"]+customer["version"])
                    # 得到版本：客户信息字典
                    version_customer_dict["cur_version"] = customer["version"]
                    version_customer_dict["customer_info"] = cust_dict
                    # 因为客户可能存在同名，将当前版本，客户信息字典加入到列表
                    customer_dict_list.append(version_customer_dict)

    if len(customer_dict_list) == 0:
        print(u"通过【" + cust + u"】未查找到可推包客户！")
        items = SearchCustomers(cust)
        if len(items) != 0:
            print(u"通过【" + cust + u"】查询到以下客户信息：")
            for custom in items:
                customerName = custom["customerName"]
                shortName = custom["shortName"]
                topCustomerName = custom["topCustomerName"]
                currProductVersion = custom["currProductVersion"]
                publishProductVersion = custom["publishProductVersion"]
                current_WFversion = ""
                publish_WFversion = ""
                for item in wf_package_list:
                    if item["name"] == currProductVersion:
                        current_WFversion = item["desc"]
                    if item["name"] == publishProductVersion:
                        publish_WFversion = item["desc"]
                if publishProductVersion != "":
                    print(u"客户名称: %s, 客户简称：%s, 顶级客户名称：%s, 当前版本：%s(%s), 已推送未更新版本：%s(%s)。" % (
                        customerName, shortName, topCustomerName, currProductVersion, current_WFversion,
                        publishProductVersion, publish_WFversion))
                else:
                    print(u"客户名称: %s, 客户简称：%s, 顶级客户名称：%s, 当前版本：%s(%s), 已推送未更新版本：无。" % (
                        customerName, shortName, topCustomerName, currProductVersion, current_WFversion))
        else:
            print(u"通过【" + cust + u"】未查找到客户信息！")
        exit()
    return customer_dict_list


def SearchCustomers(cust):
    """
    环境-生产环境，搜索工作流客户信息
    :param cust: 客户模糊名称
    :return: 返回格式：[{"customerId":"0c6181ab-1dec-4e53-b183-ff252ef89917","customerName":"临汾平阳","shortName":"临汾平阳","topCustomerName":"临汾平阳房地产开发有限公司","businessUnitName":"山西公司","totalWorkLoad":0.0,"manageName":null,"developmentPmName":null,"isExistsHotfixPackage":false,"customerLabelDtos":[{"labelId":"7ee87420-d3b8-4dd8-898d-0de47d9f3a76","name":"拓新客户","labelType":1,"sorting":0}],"erpVersionKey":null,"currProductVersion":"2.0.27.15","publishProductVersion":"","canUpProductHotfixPackageCount":0,"canUpProductHotfixPackageVersion":null,"frontlinePackageCount":0,"customizePackageCount":0,"installed":true}]
    """
    url = "https://rdc.mingyuanyun.com/rdc-dataapi-service/api/v2/customers?SearchKey=" + cust + "&IsShowNoCustomCustomer=false&ProductKey=gzlERP&Offset=0&Limit=20&OrderBy=customerId+desc"
    r = sess.get(url, headers=httphead(Authorization), proxies=proxies, verify=False)
    resp = json.loads(r.text)
    if r.status_code == 200:
        items = resp["items"]
        return items
    else:
        print(resp["error"]["message"])
        exit()


def get_customers(cust_list,wf_package_list, auto_comfirm):
    """
    得到制作更新包和推包请求需要的customers列表
    :param cust_list: 客户列表，格式[{'cur_version': '2.0.27.8', 'customer_info': {'isHavePdTask': False, 'isLock': False, 'customerName': '绿地集团', 'labels': [{'type': 1, 'id': '25be2ac9-17e4-4870-bbdf-bd2762ca89fa', 'name': '千亿客户'}], 'isFeatureApproval': False, 'isHasCustomize': False, 'tenantName': '', 'customerERP': 'b1cb6621-f0a2-4700-8089-cf53ea19a6f7,gzlERP,', 'isHotfixApproval': False, 'tenantId': '', 'isApproval': False}},...]
    :return: 返回客户信息列表，格式[
    #     {"customerName": "江苏富通置业", "customerERP": "f5d093a7-e7a1-4d65-a3ab-8d55e8d0a266,gzlERP,", "tenantId": "",
    #      "tenantName": "", "isLock": false, "isHasCustomize": false, "isApproval": false, "isHavePdTask": false,
    #      "labels": [{"id": "7ee87420-d3b8-4dd8-898d-0de47d9f3a76", "name": "拓新客户", "type": 1}, ....]
    """
    customers = []
    # 如果客户列表只有一个，直接推包，如果查到多个客户，则确认具体信息制作更新包
    if len(cust_list) == 1:
        customers.append(cust_list[0]["customer_info"])
        # 需要确认下客户
        for cust in cust_list:
            # 获取rdc版本对应的工作流版本号
            WFversion = ""
            for item in wf_package_list:
                if item["name"] == cust["cur_version"]:
                    WFversion = item["desc"]
            print(u"【%s】 当前RDC版本号: %s(%s)。" %(cust["customer_info"]["customerName"], cust["cur_version"], WFversion))
            # RDC上有可能当前客户版本是1.0.2002.2517，此类客户是未上RDC，但是装了代理服务，所以上报了此版本号。
            if cust["cur_version"].startswith("1.0.2"):
                print(u"【%s】 可能未上RDC更新通道，请确认！"%cust["customer_info"]["customerName"])
                exit()
        if auto_comfirm.lower() != "y":
            Re_comfirm = input(u"确认是否推送此客户？\n确认输入y，退出输入任意键：\n")
            if Re_comfirm.lower() != "y":
                exit()
        print(u"准备开始制作更新包，预计需要60秒。。。")
        return customers
    # 如果有客户名称和当前版本完全相同，则两个都推包
    elif len(cust_list) == 2 and cust_list[0]["cur_version"] == cust_list[1]["cur_version"] and \
            cust_list[0]["customer_info"]["customerName"] == cust_list[1]["customer_info"]["customerName"]:
        customers = [cust_list[i]["customer_info"] for i in range(len(cust_list))]
        # 需要确认下客户
        for cust in cust_list:
            print(u"【" + cust["customer_info"]["customerName"] + u"】 RDC版本号:" + cust["cur_version"])
        if auto_comfirm.lower() != "y":
            Re_comfirm = input(u"确认是否推送此客户？\n确认输入y，退出输入任意键：\n")
            if Re_comfirm.lower() != "y":
                exit()
        print(u"准备开始制作更新包，预计需要60秒。。。")
        return customers
    else:
        print(u"有名称相似客户，请确认客户信息：")
        for cust in cust_list:
            WFversion = ""
            for item in wf_package_list:
                if item["name"] == cust["cur_version"]:
                    WFversion = item["desc"]
            print(u"%s，RDC版本号：%s(%s)。" % (cust["customer_info"]["customerName"], cust["cur_version"], WFversion))
        exit()


def publishupdatepackage(versionId, customers, PackageInfo):
    """
    推包请求...
    :param versionId: 从get_tagId获取到的tagId
    :param customers: publish_customers的json中得到
    :param PackageInfo: 从makeupdatepackage返回得到，字典{"publishUpdatePackageId":29262, "sourceVersion":"2.0.33.1","publishVersion","2.0.36.1"}
    :return:
    """

    # 头信息
    headers = httphead(Authorization)
    url = "https://rdc.mingyuanyun.com/rdc-service/api/v2/apps/107/versions/" + str(versionId) + "/publishupdatepackage"
    # data = {"appId": 107, "versionId": 56092, "tenantIds": "", "customers": [
    #     {"customerName": "江苏富通置业", "customerERP": "f5d093a7-e7a1-4d65-a3ab-8d55e8d0a266,gzlERP,", "tenantId": "",
    #      "tenantName": "", "isLock": false, "isHasCustomize": false, "isApproval": false, "isHavePdTask": false,
    #      "labels": [{"id": "7ee87420-d3b8-4dd8-898d-0de47d9f3a76", "name": "拓新客户", "type": 1}],
    #      "isFeatureApproval": false, "isHotfixApproval": false, "checked": true, "disabled": false}],
    #  "publishUpdatePackageId": 29074, "isNeedManualExecute": false}
    data = {"appId": 107, "customerImageBuildRecordId": PackageInfo["customerImageBuildRecordId"], "versionId": versionId, "tenantIds": "", "customers": customers,
            "publishUpdatePackageId": PackageInfo["publishUpdatePackageId"], "isNeedManualExecute": False}

    r = sess.post(url, headers=headers, json=data, proxies=proxies, verify=False)
    if r.status_code == 200:
        for customer in customers:
            customerName = customer["customerName"]
            # 推包成功后，记录日志
            log().info(u"【%s】%s升级%s推包成功！！" % (customerName,PackageInfo["sourceVersion"],PackageInfo["publishVersion"]))
    else:
        for customer in customers:
            customerName = customer["customerName"]
            print(u"【%s】推包失败！！" % customerName)
        print(r.text)


def get_WFversion_by_RDCversion():
    """
    获取到工作流最近100个更新包
    :return: 返回100个更新包的列表信息
    """
    # 头信息
    headers = httphead(Authorization)
    # limit最大只能100，大于100请求会报错。
    url = "https://rdc.mingyuanyun.com/rdc-service/api/v2/apps/107/versions?orderBy=0&type=1&tagType=0&q=&for=all&offset=0&limit=100"
    r = sess.get(url, headers=headers, proxies=proxies, verify=False)
    if r.status_code == 200:
        resp_json = json.loads(r.text)
        items = resp_json["result"]["items"]
        # 返回版本信息字典的列表，包含RDC版本，描述desc的工作流版本，已推包客户等等。。。
        return items
    else:
        print(u"get_WFversion_by_RDCversion请求失败")
        exit()


def log():
    # 创建logger，如果参数为空则返回root logger
    logger = logging.getLogger("wup")
    logger.setLevel(logging.DEBUG)  # 设置logger日志等级

    # 如果存在logger.handlers列表为0，则创建handler
    if len(logger.handlers) == 0:
        # 创建handler
        fh = logging.FileHandler("log.txt", encoding="utf-8")  # 输出日志保存到文件
        ch = logging.StreamHandler()  # 日志打印到窗口

        # 设置输出日志格式
        formatter = logging.Formatter(
            fmt="%(asctime)s %(name)s %(filename)s %(message)s",
            datefmt="%Y/%m/%d %X")

        # 为handler指定输出格式
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)

        # 为logger添加的日志处理器
        logger.addHandler(fh)
        logger.addHandler(ch)

    # 直接返回logger
    return logger

def push_action(RDCversion, customers, auto_comfirm, desc=None, distinct=None):
    """
    执行推包过程
    :param RDCversion: "2.0.27.15"
    :param customers: 列表：["东西汇","天阜"]
    :param desc: 推包描述
    :param auto_comfirm: 如果是已确定的唯一客户，输入y直接推包
    :distinct: 是否精确匹配，None模糊匹配，输入y精确匹配
    :return: 无
    """
    # Authorization = "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjIzQjRCRkZGMTI3QzA5QTNFNzg5OTlCRTlERjYxQ0MyNzQ3NTdGQjUiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJJN1NfX3hKOENhUG5pWm0tbmZZY3duUjFmN1UifQ.eyJuYmYiOjE2MDYyOTA5MDMsImV4cCI6MTYwNjQ2MzcwMywiaXNzIjoiaHR0cHM6Ly9hdXRoLm1pbmd5dWFueXVuLmNvbSIsImF1ZCI6WyJodHRwczovL2F1dGgubWluZ3l1YW55dW4uY29tL3Jlc291cmNlcyIsImRlZmF1bHRBcGkiLCJyZGMtcmVzb3VyY2VjZW50ZXItc2VydmljZSIsInJkYy1maWxlLXNlcnZpY2UiXSwiY2xpZW50X2lkIjoicmRjIiwic3ViIjoiYzllMGMwYzYtNGYwYy00NGJlLWE1NDAtM2M1NjNiZGViMjBlIiwiYXV0aF90aW1lIjoxNjA2MjkwOTAyLCJ1c2VyIjoie1wiTmFtZVwiOlwi5ZC06bmP77yI5q2m5rGJ5Lqn5ZOB77yJXCIsXCJVc2VyTmFtZVwiOlwid3VwMDZcIixcIkVtYWlsXCI6XCJ3dXAwNkBtaW5neXVhbnl1bi5jb21cIixcIlBob25l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YuMWYfIyyuScUovTgN_SfHVljx30lG8H7jIZ0wzwdQ0ZBdVw"
    # RDCversion = "2.0.27.15"
    # desc = "1.0.2008.1312"
    # cust = u"恒泰"
    for cust in customers:
        versionlist = publish_customers(RDCversion)
        wf_package_list = get_WFversion_by_RDCversion()
        customer_dict_list = get_customer_version(cust, versionlist, wf_package_list,distinct)
        customers = get_customers(customer_dict_list, wf_package_list, auto_comfirm)
        versionId = get_tagId(RDCversion)
        if desc is None:
            # 取更新包的desc作为推包的说明
            for item in wf_package_list:
                if item["name"] == RDCversion:
                    # 转码UTF8
                    desc = item["desc"]
        print("推包更新说明："+desc)
        PackageInfo = makeupdatepackage(versionId, desc, customers)
        publishupdatepackage(versionId, customers, PackageInfo)

# if __name__ == "__main__":
    # Authorization = "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjIzQjRCRkZGMTI3QzA5QTNFNzg5OTlCRTlERjYxQ0MyNzQ3NTdGQjUiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJJN1NfX3hKOENhUG5pWm0tbmZZY3duUjFmN1UifQ.eyJuYmYiOjE2MTMyMjU2MjgsImV4cCI6MTYxMzM5ODQyOCwiaXNzIjoiaHR0cHM6Ly9hdXRoLm1pbmd5dWFueXVuLmNvbSIsImF1ZCI6WyJodHRwczovL2F1dGgubWluZ3l1YW55dW4uY29tL3Jlc291cmNlcyIsImRlZmF1bHRBcGkiLCJyZGMtcmVzb3VyY2VjZW50ZXItc2VydmljZSIsInJkYy1maWxlLXNlcnZpY2UiLCJyZGMtZXhjaGFuZ2UtYWRtaW4tc2VydmljZSJdLCJjbGllbnRfaWQiOiJyZGMiLCJzdWIiOiJjOWUwYzBjNi00ZjBjLTQ0YmUtYTU0MC0zYzU2M2JkZWIyMGUiLCJhdXRoX3RpbWUiOjE2MTMyMjU2MjcsInVzZXIiOiJ7XCJOYW1lXCI6XCLlkLTpuY_vvIjmrabmsYnkuqflk4HvvIlcIixcIlVzZXJOYW1lXCI6XCJ3dXAwNl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4g5XHghhw5mA56zoLvzFCmQkzH-_lwQB3Whd4IoWdXqLXQktvqP655s5MT3dQSOzCEu5sqSHwiTTnFZZCjsJP94aCllchekPN7dyVCYXnHHddWuSiFXj29-DJzWZt_m9qOtZGew2pgcw"
    # RDCversion = "2.0.27.15"
    # desc = "1.0.2008.1312"
    # cust = u"恒泰"
    # versionlist = publish_customers(RDCversion)
    # wf_package_list = get_WFversion_by_RDCversion()
    # customer_dict_list = get_customer_version(cust, versionlist, wf_package_list)
    # customers = get_customers(customer_dict_list, wf_package_list)
    # versionId = get_tagId(RDCversion)
    # publishUpdatePackageId = makeupdatepackage(versionId, desc, customers)
    # publishupdatepackage(versionId, customers, publishUpdatePackageId)
